package com.sunlei.webtest.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author: sun
 * @Description: 学习rabbitmq的confirm机制
 * @Data: create in 14:47 2018/11/23
 * @Modfied by:
 */
public class Producter {

    public static void main(String[] args) throws IOException, TimeoutException {
        System.out.println("-----rabbitmq 生产者 测试comfirm应答机制-----");
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        //指定消息的投递模式:confirm
        channel.confirmSelect();

        final String exchangeName = "test_confirm_exchange";
        final String routeKey = "confirm.save";

        //发送消息
        channel.basicPublish(exchangeName,routeKey,null,"test confirem".getBytes());

        /**添加一个确认监听
         * 这里使用rabbitmq提供的ConfirmListener接口
         * ConfirmListener接口需要实现两个方法:handleAck(), handleNack()
         * */
        channel.addConfirmListener(new ConfirmListener() {
            /**
             * @param deliveryTag :消息的惟一的标签
             * @param multiple :是否批量的
             * */
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("[ack 获取confirm应答]: "+deliveryTag);
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.out.println("[ack 获取confirm应答]: "+deliveryTag);
            }
        });

    }
}
